//
//  ReadData.m
//  Shine
//
//  Created by 王斌 on 16/3/14.
//  Copyright © 2016年 王斌. All rights reserved.
//

#import "ReadData.h"
#import <HealthKit/HealthKit.h>
#import "RunViewController.h"
@interface ReadData ()
@property (nonatomic, strong) HKHealthStore *healthStore;
@end

@implementation ReadData
+ (instancetype)shareInstance{
    static ReadData *readData = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        readData = [[ReadData alloc] init];
        [readData createHealthStore];
    });
    return readData;
}

- (void)createHealthStore{
    /// 判断设备是否支持健康
    if (![HKHealthStore isHealthDataAvailable]) {
        NSLog(@"设备不支持健康");
    }
    self.healthStore = [[HKHealthStore alloc] init];
    NSSet *readObjectTypes = [NSSet setWithObjects:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount], nil];
    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:readObjectTypes completion:^(BOOL success, NSError *error) {
        if (success == YES)  {
            [self readDataFromHealth];
        } else {
            //授权失败
        }
    }];

}

- (void)readDataFromHealth{
    CoreDataManager *manager = [CoreDataManager shareInstance];
    //日期在七天之内:
    NSDate *endDate = [NSDate date];
    NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate];
    timeInterval -=3600*24*7;
    NSDate *beginDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    // Use the sample type for step count
    HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    // Create a predicate to set start/end date bounds of the query
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:beginDate endDate:endDate options:HKQueryOptionStrictStartDate];
    
    // Create a sort descriptor for sorting by start date
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    
    
    HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
        if(!error && results) {
            NSString *temp = [NSString string];
            NSInteger tempCount = 0;
            for (NSInteger i = 0; i < results.count; i++) {
                HKQuantitySample *samples = results[i];
//                NSLog(@" %@: %@", samples.startDate, samples.quantity);
                ///NSDate转化成NSString
                NSString *strDate = [NSString stringWithFormat:@"%@",samples.startDate];
                ///截取时间到小时  12下标
                NSString *newData = [strDate substringToIndex:13];
                ///步数转换字符串
                NSString *tempStr = [NSString stringWithFormat:@"%@", samples.quantity];
                NSString *countStr = [tempStr stringByReplacingOccurrencesOfString:@" count" withString:@""];
                NSInteger count = [countStr integerValue];
                
                if ([newData isEqualToString:temp]) {
                    tempCount += count;
                }else{
                    if (![temp isEqualToString:@""]) {
                        [manager insertData:temp count:tempCount];
                    }
                    temp = newData;
                    tempCount = count;
                }
            }
        } else {
            //error
        }
        RunViewController *runVC = [RunViewController shareRunViewController];
        [runVC searchCount];
    }];
    [self.healthStore executeQuery:sampleQuery];
    
    
}


@end
